package normal.队列.链表实现的队列;

import normal.链表.ListNode;

/**
 * 链表实现的队列
 *
 * @author ZhuYi
 * @create 2024/12/19 15:10
 */
public class LinkedListQueue {
    private ListNode front, rear;
    private int size = 0;

    public LinkedListQueue() {
        front = null;
        rear = null;
    }

    //是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    //获取队列长度
    public int size() {
        return size;
    }

    //入队
    public void push(int num) {
        ListNode node = new ListNode(num);
        if (isEmpty()) {
            front = node;
            rear = node;
        } else {
            rear.next = node;
            rear = node;
        }
        size++;
    }

    //出队
    public void pop() {
        if (isEmpty()) throw new IndexOutOfBoundsException("队列为空");
        front = front.next;
        size--;
    }

    public int peek() {
        return front.val;
    }

    public int[] toArray() {
        ListNode node = front;
        int[] arr = new int[size()];
        for (int i = 0; i < size(); i++) {
            arr[i] = node.val;
            node = node.next;
        }
        return arr;
    }

}
